package com.app.piemoment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
import android.location.Address;
import android.os.Process;
import android.util.DisplayMetrics;
import android.view.WindowManager;
import android.widget.Toast;

import com.app.piemoment.entity.NotifyEntity;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.MKGeneralListener;
import com.baidu.mapapi.map.MKEvent;

public class PieMomentApp extends Application {

	private static final String TAG = "PieMomentApp";

	public static ArrayList<Activity> allActivity = new ArrayList<Activity>();

	public static Context appContext;

	private static int screenWidth;

	private static int screenHeight;

	private String sid;// 存储sid
	private List<Address> listAddress = new ArrayList<Address>();// 存储定位后的Address对象list
	private List<String> provincesList = new ArrayList<String>();// 存储省份数据
	private Map<String, List> citiesMap = new HashMap<String, List>();// 存储省份和城市对应数据，key=甲省名字，value=甲省下的城市list
	private Map<String, List> districtsMap = new HashMap<String, List>();// 存储城市和区县对应数据，key=乙市名字，value=乙市下的区县list
	private boolean isCheckPro = true;


	private static PieMomentApp mInstance = null;
	public boolean m_bKeyRight = true;
	public BMapManager mBMapManager = null;
	public static final String strKey = "1F572AAE2DC844C03D5AF0C9A001026E03BD1618";
	private static ArrayList<NotifyEntity> list = null;;
	/**
	 * 添加数据
	 * @param dataList
	 */
	public void addList(ArrayList<NotifyEntity> dataList) {
		if(list==null) {
			list = new ArrayList<NotifyEntity>();
		}else {
			list.clear();
		}
		list.addAll(dataList);
	}
	
	public static ArrayList<NotifyEntity> getDataList() {
		return list;
	}
	
	public boolean isCheckPro() {
		return isCheckPro;
	}

	public void setCheckPro(boolean isCheckPro) {
		this.isCheckPro = isCheckPro;
	}

	/**
	 * 获取用户session id
	 * 
	 * @return
	 */
	public String getSid() {
		return sid;
	}

	/**
	 * 设置用户session id
	 * 
	 * @param sid
	 */
	public void setSid(String sid) {
		this.sid = sid;
	}

	/**
	 * 获取信息定位信息
	 * 
	 * @return
	 */
	public List<Address> getListAddress() {
		return listAddress;
	}

	/**
	 * 添加定位地址信息集合
	 * 
	 * @param listAddress
	 *            List<android.location.Address>
	 */
	public void addListAddress(List<Address> listAddress) {
		this.listAddress.addAll(listAddress);
	}

	/**
	 * 添加定位地址信息
	 * 
	 * @param address
	 *            android.location.Address;
	 */
	public void addAddress(Address address) {
		this.listAddress.add(address);
	}

	/**
	 * 只提供简单的获取定位城市名称的函数，详细定位需要通过getListAddress()获取
	 * 
	 * @return 定位的城市名称
	 */
	public String getLocationCity() {
		if (listAddress.size() > 0) {
			String locationCity = listAddress.get(0).getLocality();
			if (locationCity == null || locationCity.trim().length() == 0) {
				locationCity = listAddress.get(0).getAdminArea();
			}
			return locationCity;
		} else {
			return null;
		}
	}

	public List<String> getProvincesList() {
		return provincesList;
	}

	public void setProvincesList(List<String> provincesList) {
		this.provincesList = provincesList;
	}

	public Map<String, List> getCitiesMap() {
		return citiesMap;
	}

	public void setCitiesMap(Map<String, List> citiesMap) {
		this.citiesMap = citiesMap;
	}

	public Map<String, List> getDistrictsMap() {
		return districtsMap;
	}

	public void setDistrictsMap(Map<String, List> districtsMap) {
		this.districtsMap = districtsMap;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		appContext = this.getApplicationContext();
		mInstance = this;
		initEngineManager(this);

		DisplayMetrics dm = new DisplayMetrics();
		WindowManager WM = (WindowManager) appContext
				.getSystemService(Context.WINDOW_SERVICE);
		WM.getDefaultDisplay().getMetrics(dm);
		screenHeight = dm.heightPixels;
		screenWidth = dm.widthPixels;
	}


	public static boolean isAppOnForeground() {
		ActivityManager activityManager = (ActivityManager) appContext
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> tasksInfo = activityManager.getRunningTasks(1);
		if (tasksInfo.size() > 0) {
			// 应用程序位于堆栈的顶层
			if ("com.app.piemoment".equals(tasksInfo.get(0).topActivity
					.getPackageName())) {
				return true;
			}
		}
		return false;
	}

	public static boolean isActivityOnForeground(Activity activity) {
		ActivityManager activityManager = (ActivityManager) appContext
				.getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> tasksInfo = activityManager.getRunningTasks(1);
		if (tasksInfo.size() > 0) {
			// activity位于堆栈的顶层
			if (activity.getClass().getName().equals(
					tasksInfo.get(0).topActivity.getClassName())) {
				return true;
			}
		}
		return false;
	}

	public static void exitApp() {
		for (Activity activity : allActivity) {
			activity.finish();
		}
		allActivity.clear();
		Process.killProcess(Process.myPid());
		System.exit(0);
	}

	public static Context getAppContext() {
		return appContext;
	}

	public static int getScreenWidth() {
		return screenWidth;
	}

	public static int getScreenHeight() {
		return screenHeight;
	}
	
	@Override
	//建议在您app的退出之前调用mapadpi的destroy()函数，避免重复初始化带来的时间消耗
	public void onTerminate() {
		// TODO Auto-generated method stub
	    if (mBMapManager != null) {
            mBMapManager.destroy();
            mBMapManager = null;
        }
		super.onTerminate();
	}
	
	public void initEngineManager(Context context) {
        if (mBMapManager == null) {
            mBMapManager = new BMapManager(context);
        }

        if (!mBMapManager.init(strKey,new MyGeneralListener())) {
            Toast.makeText(PieMomentApp.getInstance().getApplicationContext(), 
                    "BMapManager  初始化错误!", Toast.LENGTH_LONG).show();
        }
	}
	
	public static PieMomentApp getInstance() {
		return mInstance;
	}
	
	
	// 常用事件监听，用来处理通常的网络错误，授权验证错误等
    static class MyGeneralListener implements MKGeneralListener {
        
        @Override
        public void onGetNetworkState(int iError) {
            if (iError == MKEvent.ERROR_NETWORK_CONNECT) {
                Toast.makeText(PieMomentApp.getInstance().getApplicationContext(), "您的网络出错啦！",
                    Toast.LENGTH_LONG).show();
            }
            else if (iError == MKEvent.ERROR_NETWORK_DATA) {
                Toast.makeText(PieMomentApp.getInstance().getApplicationContext(), "输入正确的检索条件！",
                        Toast.LENGTH_LONG).show();
            }
            // ...
        }

        @Override
        public void onGetPermissionState(int iError) {
            if (iError ==  MKEvent.ERROR_PERMISSION_DENIED) {
                //授权Key错误：
                Toast.makeText(PieMomentApp.getInstance().getApplicationContext(), 
                        "请在检验输入的授权Key是否正确！", Toast.LENGTH_LONG).show();
                PieMomentApp.getInstance().m_bKeyRight = false;
            }
        }
    }
}
